package com.ruitu.mall_98_2.mine;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.MyRefreshBaseActivity;
import com.beanu.arad.base.my_base.base_list.ListBaseAdapter;
import com.beanu.arad.base.my_base.base_list.SuperViewHolder;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.widget.dialog.CustomAlertDialog;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.mall_98_2.mvp.contract.AddressListContract;
import com.ruitu.mall_98_2.mvp.model.AddressListModel;
import com.ruitu.mall_98_2.mvp.presenter.AddressListPresenter;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;
import com.ruitu.router_module.bean.mine.Address;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class AddressListActivity extends MyRefreshBaseActivity<AddressListPresenter, AddressListModel> implements AddressListContract.View {

    private DataAdapter adapter;
    private Bundle bundle;
    private String from;
    private List<Address> addressList;
    private String id;
    private CustomAlertDialog customAlertDialog;
    private List<Integer> skipId = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!Arad.bus.isRegistered(this)) {
            Arad.bus.register(this);
        }
        skipId.add(R.id.header);
        setLoadMoreEnabled(false);
        bundle = getIntent().getExtras();
        if (bundle != null) {
            from = bundle.getString("from");
        }
        showEmptyView(skipId);

    }

    @Override
    protected void reqData() {
        hideProgress();
        showProgress();
        mPresenter.getMineAddress(AppHolder.instance().getUser().getAccountId());
    }

    @Override
    protected RecyclerView.Adapter initAdapter() {
        adapter = new DataAdapter(this);
        return adapter;
    }

    @Override
    protected LRecyclerView findRecyclerView() {
        return findViewById(R.id.lRecyclerView);
    }

    @Override
    protected void reqFirst() {
        reqData();
    }

    @Override
    protected void reqMore() {

    }

    @Override
    protected void reReq() {

    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_address_list;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return findViewById(R.id.progress);
    }

    @Override
    protected void initViews() {
        super.initViews();
        setHeadTitle("收货地址管理");
        setRightText("添加");
    }

    @Override
    protected void onRightTextClick() {
        super.onRightTextClick();
        startActivity(AddAddressActivity.class);
    }

    @Override
    public void setData(List<Address> addresses) {
        this.addressList = addresses;
        refreshComplete();
        if (isDataEmpty(addressList)) {
            showEmptyView(skipId);
        } else {
            adapter.setDataList(addresses);
            showContent(null);
        }
    }

    @Override
    public void setFail() {
        showError(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reqData();
            }
        });
    }

    class DataAdapter extends ListBaseAdapter<Address> {

        public DataAdapter(Context context) {
            super(context);
        }

        @Override
        public int getLayoutId() {
            return R.layout.item_address;
        }

        @Override
        public void onBindItemHolder(SuperViewHolder holder, final int position) {
            TextView tv_name = holder.getView(R.id.tv_name);
            TextView tv_tel = holder.getView(R.id.tv_tel);
            TextView tv_area = holder.getView(R.id.tv_area);
            TextView tv_detailed_address = holder.getView(R.id.tv_detailed_address);
            TextView tv_address_type = holder.getView(R.id.tv_address_type);
            LinearLayout ll_item = holder.getView(R.id.ll_item);
            final Address address = mDataList.get(position);
            tv_name.setText(address.getName());
            String phone = address.getPhone();
            if (!TextUtils.isEmpty(phone)) {
//                String newAddress = phone.substring(0, 3) + "****" + phone.substring(6, 10);
                tv_tel.setText(phone);
            }
            if (TextUtils.equals(address.getStatus(), "1")) {
                tv_address_type.setVisibility(View.VISIBLE);
            } else {
                tv_address_type.setVisibility(View.GONE);
            }
            tv_area.setText(address.getProvince() + " " + address.getCity() + " " + address.getCounty());
            tv_detailed_address.setText(address.getAddress());

            ll_item.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    id = address.getId();
                    if (from == null) {
                        customAlertDialog = new CustomAlertDialog(mContext, "确定删除该收货地址吗?", new CustomAlertDialog.OkOnClickListener() {
                            @Override
                            public void OkOnClick() {
                                deletAddress();
                            }

                        });
                        customAlertDialog.show();

                    }
                    return false;
                }
            });

            ll_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra("address", addressList.get(position));
                    if (TextUtils.isEmpty(from)) {
                        intent.setClass(mContext, AddAddressActivity.class);
                        startActivity(intent);
                    } else {
                        Arad.bus.post(new EventModel<Address>(18111600, addressList.get(position)));
                        finish();
                    }
                }
            });
        }
    }

    private void deletAddress() {
        APIRetrofit.getDefault().deleteAddress(id).observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        ToastUtils.showShort("删除失败");
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        hideProgress();
                        if (baseResult.isSuccess()) {
                            customAlertDialog.dismiss();
                            reqData();
                            ToastUtils.showShort(baseResult.getMsg());
                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getResumData(EventModel eventModel) {
        if (eventModel.getEventCode() == 18061100) {
            reqData();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        reqData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }
}
